package com.itheima.advice;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.UserHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class RecordLogAdvice {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object recordLog(ProceedingJoinPoint pjp , LonOperation log)throws Throwable{
        //
        long begin = System.currentTimeMillis();
        Object returnValue = pjp.proceed();
        //
        long end = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        // 构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId()); // 需要实现 getCurrentUserId 方法
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(signature.getMethod().getName());
        operateLog.setMethodParams(pjp.getArgs()==null?"":pjp.getArgs().toString());
        operateLog.setReturnValue(returnValue==null?"":returnValue.toString());
        operateLog.setCostTime(end-begin);
        operateLogMapper.insert((operateLog));
        return returnValue;
    }

    private Integer getCurrentUserId() {
        return UserHolder.getUserId();
    }
}
